'use strict';

const mongoose = require('mongoose'),
    merchantModel = mongoose.model('Merchant');
const http = require('http');
var querystring = require('querystring');

module.exports = {
    merchantRegister: merchantRegister,
    getMerchantByLogin: getMerchantByLogin,
    getMerchantByIcnum: getMerchantByIcnum,
    merchantUpdate: merchantUpdate,
    merchantUpdateStatus2:merchantUpdateStatus2,
    updateMerchantStatus1:updateMerchantStatus1,
    openMerchant: openMerchant,
    closeMerchant: closeMerchant
}


function merchantRegister(merchant,files,callback){
    console.log(merchant);
    
      var fs = require('fs');
      var uuid = require('node-uuid');
      var icpicfile = files.icpic;
      var portraitpic = files.portraitpic;
      if(icpicfile.originalFilename!=''){
      var icpic = parseInt(Math.random()*10000000)+icpicfile.name;
      var icpicpath = "D://img/muser/iccard/"+icpic; 
      var icpicSrcPath = "http://10.222.29.187:8089/pic/muser/iccard/"+icpic;
      merchant.icpic = icpicSrcPath;
       fs.rename(icpicfile.path,icpicpath);
      }
      if(portraitpic.originalFilename!=''){
      var portrait =  parseInt(Math.random()*10000000)+portraitpic.name;
      var portraitpath = "D://img/muser/portraitfile/"+portrait;
      var portaitSrcPath = "http://10.222.29.187:8089/pic/muser/portraitfile/"+portrait;
      merchant.portait = portaitSrcPath;
       fs.rename(portraitpic.path,portraitpath);
      }
      var token = uuid.v4(); 
        merchant.token = token;
        merchant.status1 = '0';
        merchant.status2 = '1';
        merchant.operatStatus = '1';
    
     var  data={
                    name:merchant.mname,
                    icPicUrl:merchant.icpic,
                    portraitUrl:portaitSrcPath,
                    icNum:merchant.icnum,
                    token:merchant.token,
                    addr:merchant.maddr
                };
            var content = querystring.stringify(data);
            var contentLen = Buffer.byteLength(content, 'utf8');
     var option = {
         host:'10.222.29.185',
         port:8999,
         path: '/a/merchant/register',
         method: 'POST',
         headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': contentLen
               }
       };
    var req = http.request(option,function(res){
         console.log("statusCode: ", res.statusCode);
         console.log("headers: ", res.headers);
         var _data='';
        res.on('data', function(chunk){
             _data += chunk;
          });
        res.on('end', function(){
         console.log("\n--->>\nresult:",_data)
        });
    });
      req.write(content);
      req.end();      
    merchantModel.create(merchant,function(error,data){
        callback(null,data);
    });
}

function getMerchantByLogin(merchant, callback) {
     merchantModel.findOne({
         mname: merchant.mname,
         mpwd: merchant.mpwd       
     },function(error, data){
         callback(null,data);
     });
}


function merchantUpdate(merchant,files, callback){
    var fs = require('fs');
      var uuid = require('node-uuid');
      var icpicfile = files.icpic;
      var portraitpic = files.portraitpic;
      if(icpicfile.originalFilename!=''){
      var icpic = parseInt(Math.random()*10000000)+icpicfile.name;
      var icpicpath = "D://img/muser/iccard/"+icpic; 
      var icpicSrcPath = "http://10.222.29.187:8089/pic/muser/iccard/"+icpic;
      merchant.icpic = icpicSrcPath;
       fs.rename(icpicfile.path,icpicpath);
      }
      if(portraitpic.originalFilename!=''){
      var portrait =  parseInt(Math.random()*10000000)+portraitpic.name;
      var portraitpath = "D://img/muser/portraitfile/"+portrait;
      var portaitSrcPath = "http://10.222.29.187:8089/pic/muser/portraitfile/"+portrait;
      merchant.portait = portaitSrcPath;
       fs.rename(portraitpic.path,portraitpath);
      }
      
        merchant.status1 = '0';
        merchant.status2 = '1';
        merchant.operatStatus = '1';
    
     var  data={
                    name:merchant.mname,
                    icPicUrl:merchant.icpic,
                    portraitUrl:portaitSrcPath,
                    icNum:merchant.icnum,
                    addr:merchant.maddr
                };
            var content = querystring.stringify(data);
            var contentLen = Buffer.byteLength(content, 'utf8');
     var option = {
         host:'10.222.29.185',
         port:8999,
         path: '/a/merchant/register',
         method: 'POST',
         headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': contentLen
               }
       };
    var req = http.request(option,function(res){
         console.log("statusCode: ", res.statusCode);
         console.log("headers: ", res.headers);
         var _data='';
        res.on('data', function(chunk){
             _data += chunk;
          });
        res.on('end', function(){
         console.log("\n--->>\nresult:",_data)
        });
    });
      req.write(content);
      req.end();
      console.log("merchant._id：------"+merchant._id);
   merchantModel.updateOne({'_id':merchant._id},{
           mname : merchant.mname,
           mpwd  : merchant.mpwd,
           icpic : merchant.icpic,
           icnum : merchant.icnum,
           portait : merchant.portait,
           maddr   : merchant.maddr,
           status1     : merchant.status1,
           status2     : merchant.status2,
           operatStatus : merchant.operatStatus
   },function(err, doc){
        callback(null,doc);
   }); 
}



function updateMerchantStatus1(merchant){
   merchantModel.updateOne({'icnum':merchant.icnum},{status1:merchant.status},function(err, doc){
        console.log("update success");
   }); 
}

function merchantUpdateStatus2(merchant, callback){
   merchantModel.updateOne({'icnum':merchant.icnum,'token':merchant.token},{
           status2     : merchant.status2
   },function(err, doc){
        callback(null,doc);
   }); 
}

function getMerchantByIcnum(icnum,callback){
    merchantModel.findOne({'icnum' : icnum},function(err,doc){
        callback(null,doc);
    });
}

function openMerchant(merchant,callback){
   merchantModel.updateOne({'icnum':merchant.icnum},{operatStatus:'1'},function(err, doc){
        console.log("update success");
   });
}

function closeMerchant(merchant,callback){
   merchantModel.updateOne({'icnum':merchant.icnum},{operatStatus:'0'},function(err, doc){
        console.log("update success");
   });
}